package com.offcn.oauth.controller;

import com.offcn.oauth.service.AuthService;
import com.offcn.oauth.util.AuthToken;
import com.offcn.oauth.util.CookieUtil;
import com.offcn.common.entity.Result;
import com.offcn.common.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

/**
 * 身份验证控制器
 *
 * @author 30389
 * @date 2022/10/13 12:10:29
 */
@RestController
@RequestMapping(value = "/user")
public class AuthController {

    /**
     * 客户端ID
     */
    @Value("${auth.clientId}")
    private String clientId;

    /**
     * 秘钥
     */
    @Value("${auth.clientSecret}")
    private String clientSecret;

    /**
     * Cookie存储的域名
     */
    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    /**
     * Cookie生命周期
     */
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @Autowired
    AuthService authService;

    /**
     * @param username 用户名
     * @param password 密码
     * @param from     地址
     * @return {@link Result}
     */
    @PostMapping("/login")
    public Result login(String username, String password, String from) {

        if(StringUtils.isEmpty(username)){
            throw new RuntimeException("用户名不允许为空");
        }
        if(StringUtils.isEmpty(password)){
            throw new RuntimeException("密码不允许为空");
        }
        //申请令牌
        AuthToken authToken =  authService.login(username,password,clientId,clientSecret);

        System.out.println("令牌来源: " + authToken);

        //用户身份令牌
        String access_token = authToken.getAccessToken();

        System.out.println("用户身份令牌:" + access_token);

        //将令牌存储到cookie
        saveCookie(access_token, from);

        System.out.println("cookie中携带令牌的地址: " + from);

        return new Result(true, StatusCode.OK,"登录成功！:"+from);
    }

    /**
     * 将令牌存储到cookie
     *
     * @param token 令牌
     * @param from  地址
     */
    private void saveCookie(String token, String from){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response,cookieDomain,"/","Authorization",token,cookieMaxAge,false);
        //3秒后刷新页面 访问新的地址 from
        response.setHeader("Refresh","3;URL="+from);
    }
}
